package forms;

import DAO.UnidadeMedidaDAO;
import java.nio.charset.UnmappableCharacterException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.UnidadeMedida;

/**
 *
 * @author Thomas
 */
public class frmUnidadeMedida extends javax.swing.JFrame {

    boolean alterar = false;

    /**
     * Creates new form frmUnidadeMedida
     */
    public frmUnidadeMedida() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        TabPai = new javax.swing.JTabbedPane();
        TabListagem = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabUnidadeMedida = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel17 = new javax.swing.JLabel();
        txtFiltroNome = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnDeletar = new javax.swing.JButton();
        TabCadastro = new javax.swing.JPanel();
        btnGravar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtNome = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        TabPai.setPreferredSize(new java.awt.Dimension(700, 600));

        TabListagem.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tabUnidadeMedida.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Código:", "Nome:"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabUnidadeMedida);

        TabListagem.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 780, 256));
        TabListagem.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 800, 10));

        jLabel17.setText("Nome:");
        TabListagem.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
        TabListagem.add(txtFiltroNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 236, -1));

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        TabListagem.add(btnBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 10, -1, 40));

        btnNovo.setText("Novo");
        btnNovo.setMaximumSize(new java.awt.Dimension(65, 23));
        btnNovo.setMinimumSize(new java.awt.Dimension(65, 23));
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        TabListagem.add(btnNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 330, 135, -1));

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        TabListagem.add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 330, 150, -1));

        btnDeletar.setText("Deletar");
        btnDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletarActionPerformed(evt);
            }
        });
        TabListagem.add(btnDeletar, new org.netbeans.lib.awtextra.AbsoluteConstraints(353, 330, 140, -1));

        TabPai.addTab("Listagem", TabListagem);

        TabCadastro.setLayout(new java.awt.GridBagLayout());

        btnGravar.setText("Salvar");
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 50;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(18, 7, 290, 275);
        TabCadastro.add(btnGravar, gridBagConstraints);

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 38;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(18, 246, 290, 0);
        TabCadastro.add(btnCancelar, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 463;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 275);
        TabCadastro.add(txtNome, gridBagConstraints);

        jLabel2.setText("Nome:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(14, 10, 0, 0);
        TabCadastro.add(jLabel2, gridBagConstraints);

        lblCodigo.setText("0");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.ipadx = 23;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(22, 10, 0, 0);
        TabCadastro.add(lblCodigo, gridBagConstraints);

        TabPai.addTab("Cadastro", TabCadastro);

        jMenu1.setText("Fechar");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabPai, javax.swing.GroupLayout.PREFERRED_SIZE, 800, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabPai, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        if(txtNome.getText().equals("")){
        JOptionPane.showMessageDialog(this, "Campo Nome da Unidade de Medida É Necessário!");
        txtNome.requestFocus();
        }
        else{
        try {
            int UNM_ID = Integer.parseInt(lblCodigo.getText());
            String UNM_NOME = txtNome.getText();
            UnidadeMedida unm = new UnidadeMedida();
            unm.setCodigo(UNM_ID);
            unm.setNome(UNM_NOME);
            UnidadeMedidaDAO dao = new UnidadeMedidaDAO();
            if (alterar == false) {
                dao.insert(unm);
                JOptionPane.showMessageDialog(this, "Unidade de Medida Salva!");
            } else {
                dao.update(unm);
                JOptionPane.showMessageDialog(this, "Unidade de Medida Alterada!");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        atualizagrid();
        txtNome.setText("");
        TabPai.setSelectedIndex(0);
        }
    }//GEN-LAST:event_btnGravarActionPerformed
    private void atualizagrid() {
        DefaultTableModel modelo = (DefaultTableModel) tabUnidadeMedida.getModel();
        modelo.setNumRows(0);
        try {
            UnidadeMedidaDAO dao = new UnidadeMedidaDAO();
            for (UnidadeMedida u : dao.findAll()) {

                modelo.addRow(
                        new String[]{
                            "" + u.getCodigo(),
                            u.getNome(),});
            }
        } catch (Exception ex) {
        }
    }
    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        alterar = true;

        String codigo = "" + tabUnidadeMedida.getValueAt(tabUnidadeMedida.getSelectedRow(), 0);
        try {
            UnidadeMedidaDAO DAO = new UnidadeMedidaDAO();
            UnidadeMedida u = DAO.findByCodigo(Integer.parseInt(codigo));
            lblCodigo.setText(codigo);
            txtNome.setText(u.getNome());
        } catch (Exception ex) {
            Logger.getLogger(frmUnidadeMedida.class.getName()).log(Level.SEVERE, null, ex);
        }
        TabPai.setSelectedIndex(1);
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        alterar = false;
        TabPai.setSelectedIndex(1);
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        lblCodigo.setText("0");
        txtNome.setText("");
        TabPai.setSelectedIndex(0);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        lblCodigo.setVisible(false);
        atualizagrid();
    }//GEN-LAST:event_formWindowOpened

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tabUnidadeMedida.getModel();
        modelo.setNumRows(0);
        try {
            UnidadeMedidaDAO dao = new UnidadeMedidaDAO();
            for (UnidadeMedida u : dao.findByNome(txtFiltroNome.getText())) {

                modelo.addRow(
                        new String[]{
                            "" + u.getCodigo(),
                            u.getNome(),});
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletarActionPerformed
        String codigo = "" + tabUnidadeMedida.getValueAt(tabUnidadeMedida.getSelectedRow(), 0);
        try {
            UnidadeMedidaDAO DAO = new UnidadeMedidaDAO();
            DAO.delete(Integer.parseInt(codigo));
        } catch (Exception ex) {
            Logger.getLogger(frmUnidadeMedida.class.getName()).log(Level.SEVERE, null, ex);
        }
        atualizagrid();
    }//GEN-LAST:event_btnDeletarActionPerformed

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
this.dispose();
    }//GEN-LAST:event_jMenu1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmUnidadeMedida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmUnidadeMedida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmUnidadeMedida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmUnidadeMedida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmUnidadeMedida().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel TabCadastro;
    private javax.swing.JPanel TabListagem;
    private javax.swing.JTabbedPane TabPai;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDeletar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JTable tabUnidadeMedida;
    private javax.swing.JTextField txtFiltroNome;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables
}
